package com.ryder.subject.domain.service.impl;

import com.alibaba.fastjson2.JSON;
import com.ryder.subject.common.entity.PageResult;
import com.ryder.subject.common.enums.IsDeleteFlagEnum;
import com.ryder.subject.common.util.IdWorkerUtil;
import com.ryder.subject.common.util.LoginUtil;
import com.ryder.subject.domain.convert.SubjectInfoConvert;
import com.ryder.subject.domain.entity.SubjectInfoBO;
import com.ryder.subject.domain.entity.SubjectOptionBO;
import com.ryder.subject.domain.handler.subject.SubjectTypeHandler;
import com.ryder.subject.domain.handler.subject.SubjectTypeHandlerFactory;
import com.ryder.subject.domain.redis.RedisUtil;
import com.ryder.subject.domain.service.SubjectInfoDomainService;
import com.ryder.subject.domain.service.SubjectLikedDomainService;
import com.ryder.subject.infra.basic.entity.SubjectInfo;
import com.ryder.subject.infra.basic.entity.SubjectInfoEs;
import com.ryder.subject.infra.basic.entity.SubjectLabel;
import com.ryder.subject.infra.basic.entity.SubjectMapping;
import com.ryder.subject.infra.basic.service.SubjectEsService;
import com.ryder.subject.infra.basic.service.SubjectInfoService;
import com.ryder.subject.infra.basic.service.SubjectLabelService;
import com.ryder.subject.infra.basic.service.SubjectMappingService;
import com.ryder.subject.infra.entity.UserInfo;
import com.ryder.subject.infra.rpc.UserRPC;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.ZSetOperations;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.CollectionUtils;

import java.util.*;

/**
 * 描述: 题目信息表(SubjectInfo)表服务实现类
 *
 * @author Ryder
 * @version 1.0
 * @since 1.0 // 版本号，指明从哪个版本开始
 * 更新日期: 2025/02/05
 */

@Service
@Slf4j
public class SubjectInfoDomainServiceImpl implements SubjectInfoDomainService {

    @Autowired
    private SubjectInfoService subjectInfoService;

    @Autowired
    private SubjectMappingService subjectMappingService;

    @Autowired
    private SubjectLabelService subjectLabelService;

    //注入工厂
    @Autowired
    private SubjectTypeHandlerFactory subjectsTypeHandlerFactory;

    @Autowired
    private SubjectEsService subjectEsService;

    @Autowired
    private UserRPC userRPC;

    @Autowired
    private RedisUtil redisUtil;

    private static final String RANK_KEY = "subject_rank";
    @Autowired
    private SubjectLikedDomainService subjectLikedDomainService;

    /**
     * 添加题目
     *
     * @param subjectInfoBO 实体对象
     * @return 成功：true，失败：false
     */
    @Override
    @Transactional(rollbackFor = Exception.class)
    public void add(SubjectInfoBO subjectInfoBO) {
        if (log.isInfoEnabled()) {
            log.info("SubjectInfoDomainServiceImpl.add.bo:{}", JSON.toJSONString(subjectInfoBO));
        }
        //对应题型的表
        //工厂+策略的形式 包含了 4种类型，根据传入的type自动映射选择处理
        SubjectInfo subjectInfo = SubjectInfoConvert.INSTANCE.convertBoToInfo(subjectInfoBO);
        subjectInfo.setIsDeleted(IsDeleteFlagEnum.UN_DELETED.getCode());
        //操作主表
        subjectInfoService.insert(subjectInfo);
        //开始工厂+策略
        SubjectTypeHandler handler = subjectsTypeHandlerFactory.getHandler(subjectInfo.getSubjectType());
        subjectInfoBO.setId(subjectInfo.getId());
        //调用对应提醒handler的add方法
        handler.add(subjectInfoBO);

        //Mapping表
        List<Integer> categoryIds = subjectInfoBO.getCategoryIds(); // 获取分类ID列表
        List<Integer> labelIds = subjectInfoBO.getLabelIds(); // 获取标签ID列表
        List<SubjectMapping> mappingList = new LinkedList<>();
        categoryIds.forEach(categoryId -> {
            labelIds.forEach(labelId -> {
                SubjectMapping subjectMapping = new SubjectMapping();
                subjectMapping.setSubjectId(subjectInfo.getId());
                subjectMapping.setCategoryId(Long.valueOf(categoryId));
                subjectMapping.setLabelId(Long.valueOf(labelId));
                subjectMapping.setIsDeleted(IsDeleteFlagEnum.UN_DELETED.getCode());
                mappingList.add(subjectMapping);
            });
        });

        subjectMappingService.batchInsert(mappingList);
        //同步到es
        SubjectInfoEs subjectInfoEs = new SubjectInfoEs();
        subjectInfoEs.setDocId(new IdWorkerUtil(1, 1, 1).nextId());
        subjectInfoEs.setSubjectId(subjectInfo.getId());
        subjectInfoEs.setSubjectAnswer(subjectInfoBO.getSubjectAnswer());
        subjectInfoEs.setCreateTime(new Date().getTime());
        subjectInfoEs.setCreateUser("ryder");
        subjectInfoEs.setSubjectName(subjectInfo.getSubjectName());
        subjectInfoEs.setSubjectType(subjectInfo.getSubjectType());
        subjectEsService.insert(subjectInfoEs);
        //redis放入zadd计入排行榜
        redisUtil.addScore(RANK_KEY, LoginUtil.getLoginId(), 1);
    }

    @Override
    public PageResult<SubjectInfoBO> getSubjectPage(SubjectInfoBO subjectInfoBO) {
        //要返回 先new出来
        PageResult<SubjectInfoBO> pageResult = new PageResult<>();
        pageResult.setPageNo(subjectInfoBO.getPageNo());
        pageResult.setPageSize(subjectInfoBO.getPageSize());
        int start = (subjectInfoBO.getPageNo() - 1) * subjectInfoBO.getPageSize();
        SubjectInfo subjectInfo = SubjectInfoConvert.INSTANCE.convertBoToInfo(subjectInfoBO);
        int count = subjectInfoService.countByCOndition(subjectInfo, subjectInfoBO.getCategoryId()
                , subjectInfoBO.getLabelId());
        if (count == 0) {
            return pageResult;
        }
        List<SubjectInfo> subjectInfoList = subjectInfoService.queryPage(subjectInfo, subjectInfoBO.getCategoryId()
                , subjectInfoBO.getLabelId(), start, subjectInfoBO.getPageSize());
        List<SubjectInfoBO> subjectInfoBOList = SubjectInfoConvert.INSTANCE.convertInfoToBoList(subjectInfoList);
        pageResult.setRecords(subjectInfoBOList);
        pageResult.setTotal(count);
        return pageResult;
    }

    /**
     * 查询题目信息
     *
     * @param subjectInfoBO 实体对象
     * @return 实体对象
     */
    @Override
    public SubjectInfoBO querySubjectInfo(SubjectInfoBO subjectInfoBO) {
        SubjectInfo subjectInfo = subjectInfoService.queryById(subjectInfoBO.getId());

        SubjectTypeHandler handler = subjectsTypeHandlerFactory.getHandler(subjectInfo.getSubjectType());
        SubjectOptionBO optionBO = handler.query(subjectInfo.getId());
        SubjectInfoBO bo = SubjectInfoConvert.INSTANCE.convertOptionAndInfoToBo(optionBO, subjectInfo);

        //查对应的labelNames
        SubjectMapping subjectMapping = new SubjectMapping();
        subjectMapping.setSubjectId(subjectInfo.getId());
        subjectMapping.setIsDeleted(IsDeleteFlagEnum.UN_DELETED.getCode());
        List<SubjectMapping> subjectMappingList = subjectMappingService.queryLabelId(subjectMapping);
        //拿到mapping中对应的label id
        List<Long> labelIds = subjectMappingList.stream()
                .map(SubjectMapping::getLabelId)
                .toList();
        if (CollectionUtils.isEmpty(labelIds)) {
            return bo;
        }
        List<SubjectLabel> subjectLabelList = subjectLabelService.batchQueryById(labelIds);
        //通过一堆label id 在 label 表中查出labelName
        List<String> labelNames = subjectLabelList.stream()
                .map(SubjectLabel::getLabelName)
                .toList();
        //转换
        bo.setLabelNames(labelNames);
        //封装是否点赞过
        bo.setLiked(subjectLikedDomainService.isLiked(String.valueOf(subjectInfoBO.getId()), LoginUtil.getLoginId()));
        bo.setLikedCount(subjectLikedDomainService.getLikedCount(String.valueOf(subjectInfoBO.getId())));
        log.info("SubjectInfoDomainServiceImpl.querySubjectInfo.bo:{}", JSON.toJSONString(bo));
        assembleSubjectCursor(subjectInfoBO, bo);
        return bo;
    }

    private void assembleSubjectCursor(SubjectInfoBO subjectInfoBO, SubjectInfoBO bo) {
        Long categoryId = subjectInfoBO.getCategoryId();
        Long labelId = subjectInfoBO.getLabelId();
        Long subjectId = subjectInfoBO.getId();
        if (Objects.isNull(categoryId) || Objects.isNull(labelId)) {
            return;
        }

        SubjectMapping subjectMapping = new SubjectMapping();
        subjectMapping.setSubjectId(subjectId);
        subjectMapping.setCategoryId(categoryId);
        subjectMapping.setLabelId(labelId);
        subjectMapping.setIsDeleted(IsDeleteFlagEnum.UN_DELETED.getCode());
        SubjectMapping result = subjectMappingService.queryAllByLimit(subjectMapping);
        if (result == null) {
            return;
        }

        Long nextSubjectId = subjectInfoService.querySubjectIdCursor(subjectId, categoryId, labelId, 1);
        if (!Objects.isNull(nextSubjectId)) {
            bo.setNextSubjectId(nextSubjectId);
        }
        Long lastSubjectId = subjectInfoService.querySubjectIdCursor(subjectId, categoryId, labelId, 0);
        if (!Objects.isNull(lastSubjectId)) {
            bo.setLastSubjectId(lastSubjectId);
        }
    }

    /**
     * 全文高亮关键词搜索
     *
     * @param subjectInfoBO 实体对象
     * @return SubjectInfoEs 对象
     */
    @Override
    public PageResult<SubjectInfoEs> getSubjectPageBySearch(SubjectInfoBO subjectInfoBO) {
        SubjectInfoEs subjectInfoEs = new SubjectInfoEs();
        subjectInfoEs.setPageNo(subjectInfoBO.getPageNo());
        subjectInfoEs.setPageSize(subjectInfoBO.getPageSize());
        subjectInfoEs.setKeyWord(subjectInfoBO.getKeyWord());
        return subjectEsService.querySubjectList(subjectInfoEs);
    }

    @Override
    public List<SubjectInfoBO> getContributeList() {
        Set<ZSetOperations.TypedTuple<String>> typedTuples = redisUtil.rankWithScore(RANK_KEY, 0, 5);
        if (log.isInfoEnabled()) {
            log.info("SubjectInfoDomainServiceImpl.getContributeList.typedTuples：{}", JSON.toJSONString(typedTuples));
        }
        if (CollectionUtils.isEmpty(typedTuples)) {
            return Collections.emptyList();
        }
        List<SubjectInfoBO> boList = new LinkedList<>();
        typedTuples.forEach(rank -> {
            SubjectInfoBO subjectInfoBO = new SubjectInfoBO();
            subjectInfoBO.setSubjectCount(rank.getScore().intValue());
            //获取用户对象、头像、昵称等信息
            UserInfo userInfo = userRPC.getUserInfo(rank.getValue());
            subjectInfoBO.setCreateUser(userInfo.getNickName());
            subjectInfoBO.setCreateUserAvatar(userInfo.getAvatar());
            boList.add(subjectInfoBO);
        });
        return boList;
    }
}
